#include "ET++.ph"
#ifdef __GNUG__
#pragma implementation
#endif

#include "TextItem.h"

#include "Class.h"
#include "String.h"
#include "Look.h"

//---- TextItem ----------------------------------------------------------------

NewMetaImpl(TextItem,VObject, (TP(text), TP(font), T(border)));

TextItem::TextItem(const char *t, Font *f, const Point &b)
							: font(f), border(b), VObject(cIdNone)
{
	SetFlag(eVObjVFixed);
	text= strsave(t);
	SetContentRect(Rectangle(GetOrigin(), GetMinSize().extent), FALSE);
}

TextItem::TextItem(int id, const char *t, Font *f, const Point &b)
							: font(f), border(b), VObject(id)
{
	SetFlag(eVObjVFixed);
	text= strsave(t);
	SetContentRect(Rectangle(GetOrigin(), GetMinSize().extent), FALSE);
}

TextItem::~TextItem()
{
	SafeDelete(text);
}

void TextItem::SetString(const char *t, bool redraw)
{
	strreplace(&text, t);
	SetContentRect(Rectangle(GetOrigin(), GetMinSize().extent), redraw);
	Changed();
}

void TextItem::SetFString(bool redraw, const char *va_(fmt), ...)
{
	va_list ap;
	va_start(ap,va_(fmt));
	strvreplace(&text, va_(fmt), ap);
	SetContentRect(Rectangle(GetOrigin(), GetMinSize().extent), redraw);
	Changed();
	va_end(ap);
}

void TextItem::SetFont(Font *fp, bool redraw)
{
	if (font != fp) {
		font= fp;
		SetContentRect(Rectangle(GetOrigin(), GetMinSize().extent), redraw);
	}
}

Metric TextItem::GetMinSize()
{
	return font->GetMetric(text).Expand(border);
}

const char *TextItem::AsString()
{
	return text;
}

void TextItem::Draw(Rectangle)
{
	if (text && *text) {
		Point p(contentRect.origin+border);
		p.y+= font->Ascender();
		GrShowString(font, Enabled() ? gInkBlack
									: gLook->DisableInk(), p, (byte*)text);
	}
}

int TextItem::Compare(Object *op)
{
	return StrCmp(text, Guard(op,TextItem)->text, -1, gStdEncoding->SortMap());
}

bool TextItem::IsEqual(Object *op)
{
	if (op && op->IsKindOf(TextItem))
		return StrCmp(AsString(), op->AsString(), -1, gStdEncoding->SortMap()) == 0;
	return FALSE;
}

OStream& TextItem::PrintOn(OStream &s)
{
	VObject::PrintOn(s);
	s << font SP << border SP;
	return s.PrintString(text);
}

IStream& TextItem::ReadFrom(IStream &s)
{
	SafeDelete(text);
	VObject::ReadFrom(s);
	s >> font >> border;
	return s.ReadString(&text);
}
